<template>
  <div class="main">
    <el-form class="btn_con" v-model="form">
      <el-row gutter="8">
        <el-col :span="4">
          <el-form-item label="">
            <el-input clearable v-model="queryForm.name" placeholder="请输入客户" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-input clearable v-model="queryForm.keyword" placeholder="请输入产品" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-select clearable v-model="queryForm.inquiryStatus" placeholder="请选择状态">
              <el-option
                v-for="item in inquiryStatusList"
                :key="item.dictSort"
                :label="item.dictLabel"
                :value="item.dictSort"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" v-if="viewType !== 'customer'">
          <el-form-item label="">
            <el-select clearable v-model="queryForm.advancedSearch" placeholder="请选择高级搜索">
              <el-option
                v-for="item in advancedList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="add_btn">
          <el-button @click="handleQuery" type="primary">搜索</el-button>
          <el-button @click="handleReset" type="primary">重置</el-button>
          <el-button v-if="viewType === 'customer'" @click="handleAdd" type="primary">新增客户</el-button>
          <el-button @click="handleChangeView" type="primary">
            {{ viewType === 'customer' ? '按询盘展示' : '按客户展示' }}
          </el-button>
        </el-col>
      </el-row>
    </el-form>
    <div v-if="viewType === 'customer'">
      <el-table :data="tableData" style="width: 100%" :height="tableHeight" v-loading="loading" element-loading-svg-view-box="0, 0, 1024, 1024" :element-loading-svg="LoadingSvg">
        <el-table-column type="expand">
          <template #default="props">
            <div class="inquuiry_table">
              <InquiryTable :inquiry-status-list="inquiryStatusList" :inquiryStatusMap="inquiryStatusMap"  :ref="el => handdlerAddRef(el, props.row.id)" :customerId="props.row.id" type="expand" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="name" label="客户名称" />  
        <el-table-column prop="company" label="公司名称" width="180" />      
        <el-table-column prop="asi" label="ASI编号" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" plain size="small" @click="handleAddInquiry(scope.row)">新增询盘</el-button>
            <!-- <el-button type="primary" plain size="small" @click="handleAddInquiry(scope.row)">新增询盘/订单</el-button> -->
            <el-button plain type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button plain type="primary" size="small" @click="handleDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination_con">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pagination.page"
          :total="pagination.total"
          small background layout="prev, pager, next"
        />
      </div>
      <AddModal ref="AddModalRef" @close="handlerClose" />
      <AddInquiryModal ref="AddInquiryModalRef" v-model="showAddInquiry" id="addInquiryModal" @close="handlerInquiryClose"/>
    </div>
    <InquiryTable :inquiry-status-list="inquiryStatusList" :inquiryStatusMap="inquiryStatusMap" ref="inquiryTableRef" :queryForm="queryForm" type="page" v-else />
  </div>
</template>
  
<script lang="ts" setup>
import { ref, onMounted, defineAsyncComponent } from 'vue';
import api from '/@/api/email/index';
import { LoadingSvg } from '/@/utils/loading';
import commonApi from '/@/api/common';
import { Local } from '/@/utils/storage';
import { useEmail } from '/@/stores/email';
import pinia from '/@/stores';

defineOptions({ name: 'customer' });

const AddModal = defineAsyncComponent(() => import('./addModal.vue'));
const AddInquiryModal = defineAsyncComponent(() => import('./addInquiryModal.vue'));
const InquiryTable = defineAsyncComponent(() => import('./inquiryTable.vue'));

const inquiryStatusList = ref<any>([]);
const inquiryStatusMap = ref<any>({});
const tableData = ref([]);
// const route = useRoute();
const tableHeight = ref(500);
const viewType = ref(Local.get('customer_page_type') || 'customer');

const AddModalRef = ref()
const form = ref<any>({});
const queryForm = ref<any>({});
const AddInquiryModalRef = ref()
const showAddInquiry = ref(false);
const inquiryForm = ref({
  clientId: '',
});
const loading = ref(false);
const inquiryTables = ref<any>({});
const inquiryTableRef = ref();
const stores = useEmail(pinia);
const advancedList = [{
  value: 'followup',
  label: '需要跟进'
}, {
  value: 'deliver',
  label: '临近发货'
}, {
  value: 'delivery',
  label: '临近交期'
}];

const pagination = ref({
  page: 1,
  size: 10,
  total: 0
});

const handdlerAddRef = (el: any, id: string) => {
  if (el) {
    inquiryTables.value[id] = el;
  }
};

const handleQuery = () => {
  if (viewType.value === 'customer') {
    pagination.value.page = 1;
    getList();
  } else {
    if (inquiryTableRef.value) {
      inquiryTableRef.value.search();
    }
  }
};

const handleReset = () => {
  queryForm.value = {};
};

const getList = async () => {
  const account = stores.curAccount;
  loading.value = true;
  const res = await api.client.getList({
    emailAccount: account,
    pageNum: pagination.value.page,
    pageSize: pagination.value.size,
    ...queryForm.value
  });
  loading.value = false;
  if (res.code === 200) {
    tableData.value = res.data;
    pagination.value.total = res.total;
  }
};

const handleDel = async (row: any) => {
  ElMessageBox.confirm('确认删除吗?', { cancelButtonText: '取消', confirmButtonText: '确认' }).then(async () => {
    const res = await api.client.delClient(row.id);
    if (res.code === 200) {
      ElMessage({ type: 'success', message: '操作成功' });
      getList();
    }
  });
};

const handleEdit = (row: any) => {
  AddModalRef.value.showDialog = true
  AddModalRef.value.form = { ...row }
};

const handleChangeView = () => {
  if (viewType.value === 'customer') {
    viewType.value = 'inquiry';
  } else {
    viewType.value = 'customer';
  }
  Local.set('customer_page_type', viewType.value);
};

// 新增询盘/订单
const handleAddInquiry = (row: any) => {
  showAddInquiry.value = true
  AddInquiryModalRef.value.form.clientId = row.id
  inquiryForm.value = {
    clientId: row.id
   };
};

const handleAdd = () => {
  AddModalRef.value.showDialog = true
  AddModalRef.value.form = {
    emailAccount: stores.curAccount
  }
};

const handlerClose = async (refresh?: boolean) => {
  AddModalRef.value.showDialog = false
  if (viewType.value !== 'customer') {
    handleChangeView();
    return;
  }
  if (refresh) {
    if (form.value.id) {
      const res = await api.client.getDetail(form.value.id);
      if (res.code === 200) {
        const item: any = tableData.value.find((item: any) => item.id === form.value.id);
        if (item) {
          Object.assign(item, res.data);
        } else {
          getList();
        }
      }
    } else {
      getList();
    }
  }
};

const handlerInquiryClose = () => {
  const tableRef = inquiryTables.value[inquiryForm.value.clientId];
  if (tableRef) {
    tableRef.search();
  }
};

const handleCurrentChange = (page: number) => {
  pagination.value.page = page;
  getList();
};

const getDict = async () => {
  const res = await commonApi.getDictData('inquiry_status');
  if (res.code === 200) {
    inquiryStatusList.value = res.data;
    inquiryStatusMap.value = inquiryStatusList.value.reduce((obj: any, item) => {
      obj[item.dictSort] = item.dictLabel;
      return obj;
    }, {});
  }
};

onMounted(() => {
  getList();
  getDict();

  const setTableHeight = () => {
    tableHeight.value = window.innerHeight - 130 // 80 为顶部距离，根据实际情况设置
  }
  setTableHeight()
  window.addEventListener('resize', setTableHeight);
});
</script>
<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100vh;
  padding: 20px;
}

.pagination_con {
  display: flex;
  justify-content: end;
  padding: 10px;
  background: #fff;
}

.btn_con {
  padding: 7px 10px;
  margin-bottom: 10px;
}

.add_btn {
  flex: 1;
  display: flex;
  justify-content: right;
  align-items: center;
}

.inquuiry_table {
  margin-left: 30px;
}
</style>
  